package com.spring.controller;

import com.spring.annotation.RequiredLog;
import com.spring.dao.ArticleDao;
import com.spring.dao.ArticleTagDao;
import com.spring.pojo.Article;
import com.spring.pojo.JsonResult;
import com.spring.pojo.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * @author 黄嘉强
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private ArticleTagDao articleTagDao;
    /**
     * 新增一篇文章
     * @param article 文章对象
     * @return 如果新增成功则返回"create ok"
     */
    @PostMapping
    public JsonResult doCreate(@RequestBody Article article) {
        // 为文章设置时间
        article.setCreatedTime(new Date());
        article.setModifiedTime(new Date());

        // 从客户端传来的请求中获取tagIds数组
        List<Tag> tags = article.getTags();
        List<Integer> tagIds = new ArrayList<>(tags.size());
        for (Tag t:tags) {
            tagIds.add(t.getId());
        }

        // 插入article表和article_tag表
        articleDao.insert(article);
        articleTagDao.insert(article.getId(), tagIds.toArray(new Integer[]{}));

        return new JsonResult("create ok");
    }

    /**
     * 基于id查询文章信息
     * @param id 文章id
     * @return 如果查询成功则返回查询到的文章信息
     */
    @RequiredLog(operation = "浏览文章")
    @GetMapping("/{id}")
    public JsonResult doSelectById(@PathVariable("id") Integer id) {
        Article article = articleDao.selectById(id);
        return new JsonResult(article);
    }
}
